function parelleTask(
  tasks: any[],
  parelleCount = 5,
  onProgress?: (progress: number) => void
) {
  return new Promise((resolve, reject) => {
    if (tasks.length == 0) {
      resolve(null);
      return;
    }
    let nextIndex = 0;
    let finishedCount = 0;
    const totalTasks = tasks.length;

    // 更新进度
    function updateProgress() {
      if (onProgress) {
        const progress = (finishedCount / totalTasks) * 100;
        onProgress(progress);
      }
    }
    function _run() {
      const task = tasks[nextIndex];
      nextIndex++;
      task()
        .then(() => {
          finishedCount++;
          updateProgress();
          if (nextIndex < tasks.length) {
            _run();
          } else if (finishedCount == tasks.length) {
            resolve(null);
          }
        })
        .catch((err: any) => {
          updateProgress();
          reject(err);
        });
    }

    for (let i = 0; i < parelleCount && i < tasks.length; i++) {
      _run();
    }
  });
}

// 请求队列,使用类
class RequestQueue {
  private queue: (() => Promise<any>)[] = [];
  private activePromises: Set<Promise<any>> = new Set();
  private maxConcurrency: number;
  private progressCallbacks: ((progress: number) => void)[] = [];
  private totalTasks = 0;
  private completedTasks = 0;

  constructor(maxConcurrency = 3) {
    this.maxConcurrency = maxConcurrency;
  }

  async add(request: () => Promise<any>): Promise<any> {
    this.totalTasks++;
    this.updateProgress();

    // 等待有可用的并发槽位
    while (this.activePromises.size >= this.maxConcurrency) {
      await Promise.race(this.activePromises);
    }

    const promise = request();
    this.activePromises.add(promise);

    promise.finally(() => {
      this.activePromises.delete(promise);
      this.completedTasks++;
      this.updateProgress();
    });

    return promise;
  }

  private updateProgress() {
    const progress = this.totalTasks === 0 
      ? 100 
      : (this.completedTasks / this.totalTasks) * 100;
    
    requestAnimationFrame(() => {
      this.progressCallbacks.forEach(cb => cb(progress));
    });
  }

  onProgress(callback: (progress: number) => void) {
    this.progressCallbacks.push(callback);
    return this;
  }

  async waitForAll(): Promise<void> {
    while (this.activePromises.size > 0) {
      await Promise.race(this.activePromises);
    }
  }

  getProgress(): number {
    return this.totalTasks === 0 
      ? 100 
      : (this.completedTasks / this.totalTasks) * 100;
  }
}

export { parelleTask, RequestQueue };
